import {guid} from '@/utils/CommonUtils';

export function createFormDefinition() {
  return {
    id: guid(),
    formName: '单据名称',
    formKey: undefined,
    tableName: undefined,
    fields: [],
    subForms: [],
    formMain: true,//主表
    views: [createFormView(true)],
    fieldLastIndex: 0,
    subTableIndex: 0,
    hasFlow: false,

    //下面是一些子表字段
    actions: [],
    menus: [],
    flows: [],
    relations: [],
    triggers: [],
    fieldValueFormulaGroups: [],
    fieldActionFormulaGroups: [],
    fieldClearFormulas: [],
    formCheckGroups: [],
    subFormAuthFormulas: [],
    uniqueConfigs: [],
    blockContainers: [],
    blockContainerHideFormulas: [],
    pageSize: 20,
    changePageSizeAble: false,
    initRows: 1
  };
}

export function createFormView(mainView = false) {
  return {
    id: guid(),
    html: '',
    templateConfigs: [],
    pageWidth: 960,
    viewName: mainView ? '主视图' : '新建视图',
    mainView,
    layoutView: false,
    mobileView: false,
    layoutFieldNameFormula: undefined,
    layoutFieldNameFormulaTitle: undefined,
    components: []
  }
}

export function readFormDefinitionVo(formDefinitionVo) {
  formDefinitionVo = formDefinitionVo || {};
  formDefinitionVo = JSON.parse(JSON.stringify(formDefinitionVo));
  readFieldsVO(formDefinitionVo.fields || []);
  readViewsVO(formDefinitionVo.views || []);
  readSubFormVo(formDefinitionVo.subForms || []);
  readMenus(formDefinitionVo.menus || []);
  readRelations(formDefinitionVo.relations || []);
  return formDefinitionVo;
}

function readFieldsVO(fields) {
  fields.forEach(f => {
    f.exts = f.exts && JSON.parse(f.exts) || [];
  });
}

function readViewsVO(views) {
  views.forEach(view => {
    view.components = view.components && JSON.parse(view.components) || [];
    view.templateConfigs = view.templateConfigs && JSON.parse(view.templateConfigs) || undefined;
  });
}

function readSubFormVo(subForms) {
  subForms.forEach(subForm => {
    readFieldsVO(subForm.fields || []);
  });
}

function readMenus(menus) {
  menus.forEach(menu => {
    let buttons = menu.buttons || [];
    buttons.forEach(button => {
      button.config = JSON.parse(button.config) || {};
    });
  });
}

function readRelations(relations) {
  (relations || []).forEach(relation => {
    (relation.manuals || []).forEach(manual => {
      (manual.buttons || []).forEach(button => {
        try {
          button.config = JSON.parse(button.config)
        } catch(e) {
        }
      })
    })
  })
}
